/* eslint-disable*/
import { BasicTableProps } from '/@/components/BasicTable/type/BasicTableProps';
import { TableActionType } from '/@/components/BasicTable/type/TableActionType';
import { isProdMode } from '/@/utils/env/env';
import { onUnmounted, ref, unref, watch, WatchStopHandle } from 'vue';
import { getDynamicProps } from '/@/utils';
import { error } from '/@/utils/log';
import { DynamicProps } from '/#/utils';
import { FormActionType } from '/@/components/BasicForm/type/form';
import { FetchParams } from '/@/components/BasicTable/type/table';

type Props = Partial<DynamicProps<BasicTableProps>>;

export function useBasicTable(tableProps: Props): [(instance: TableActionType) => void, TableActionType] {
  const tableRef = ref<Nullable<TableActionType>>(null);

  let stopWatch: WatchStopHandle;

  function register(instance: TableActionType) {
    isProdMode() &&
      onUnmounted(() => {
        tableRef.value = null;
      });
    if (isProdMode() && instance === unref(tableRef)) return;
    tableRef.value = instance;
    tableProps && instance.setProps(getDynamicProps(tableProps));
    stopWatch?.();

    stopWatch = watch(
      () => tableProps,
      () => {
        tableProps && instance.setProps(getDynamicProps(tableProps));
      },
      {
        immediate: true,
        deep: true,
      }
    );
  }

  function getTableInstance() {
    const table = unref(tableRef);
    if (!table) {
      error(
        'The table instance has not been obtained yet, please make sure the table is presented when performing the table operation!'
      );
    }
    return table as TableActionType;
  }

  const methods: TableActionType & {
    getForm: () => FormActionType;
  } = {
    reload: async () => {
      return await getTableInstance().reload();
    },
    setProps: (props: Partial<BasicTableProps>) => {
      getTableInstance().setProps(props);
    },
    getDataSource: () => {
      return getTableInstance().getDataSource();
    },
    setTableData: (values: any[]) => {
      return getTableInstance().setTableData(values);
    },
  };

  return [register, methods];
}
